package com.oceansoft.mobile.econsole.weixin.controller;


import com.oceansoft.mobile.econsole.weixin.entity.VertifyUserBean;
import com.oceansoft.mobile.econsole.weixin.util.ObjectJsonSerializer;
import com.tmri.comm.pps.ProtocolConstants;
import com.tmri.comm.pps.client.IObjectByteArrayConverter;
import com.tmri.comm.pps.client.NetServiceInvoker;
import com.tmri.comm.pps.client.bean.AesResult;
import com.tmri.comm.pps.client.bean.AesToken;
import com.tmri.comm.pps.client.bean.CryptInfo;
import com.tmri.comm.pps.comm.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;


/**
 * Created by xuhb on 2017/3/27.
 */
@Controller
@RequestMapping(value = "check122")
public class Login122Controller {
    private static final Logger log = LoggerFactory.getLogger(Login122Controller.class);
    //服务地址，当前为测试环境，
    //实际线上环境为：http://各省122平台域名+/ws。
    static final String server = "http://sd.122.gov.cn/ws";

    NetServiceInvoker invoker;//调用服务端的封装类

    String apiUrl = server + "/m/uservertify/api";//请求服务API地址，固定

    String siteId = "000001";//用户互认接口，本参数无效
    String serverId = "000000";//服务端id，固定00000
    String clientId = "000346";//客户端id，生产环境由我们分配。

    public static AesToken token;//存储AES对称加密秘钥类

    protected static String result;

    @RequestMapping(value="login")
    @ResponseBody
    public String jiaojing(HttpServletRequest request) throws Exception{
        before();
        String r1 = null;
        String sfzmmc = request.getParameter("sfzmmc"); //"A"
        String sfzmhm = request.getParameter("sfzmhm"); //"32128119910414665X"
        String sjhm = request.getParameter("sjhm");// "18762660753"
        try {
            r1 = isRegister(sfzmmc,sfzmhm,sjhm);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

        //return "123";
    }



    public void before() {
        //第一步：构造NetServiceInvoker，需要两个参数：分别是：BaseHttpCryptData和IObjectByteArrayConverter
        invoker = new NetServiceInvoker(
                //参数一：NetServiceInvoker的加解密封装类，采用模板模式，只需要实现如下接口
                new BaseHttpCryptData() {
                    //(1)互联网服务平台公钥，由互联网服务平台统一分配.
                    @Override
                    public String getPublicKey(CryptInfo cryptInfo) {
                        return "MIICOzCCAaSgAwIBAgIEVvNRsDANBgkqhkiG9w0BAQQFADBiMQkwBwYDVQQGEwAxCTAHBgNVBAgT\n" +
                                "ADETMBEGA1UEBxMKMjAyMC0xMi0zMTETMBEGA1UEChMKMjAxNi0wMy0wNTEPMA0GA1UECxMGc3lz\n" +
                                "dGVtMQ8wDQYDVQQDEwYwMDAwMDAwHhcNMTYwMzI0MDIzMjE2WhcNMjYwMzIyMDIzMjE2WjBiMQkw\n" +
                                "BwYDVQQGEwAxCTAHBgNVBAgTADETMBEGA1UEBxMKMjAyMC0xMi0zMTETMBEGA1UEChMKMjAxNi0w\n" +
                                "My0wNTEPMA0GA1UECxMGc3lzdGVtMQ8wDQYDVQQDEwYwMDAwMDAwgZ8wDQYJKoZIhvcNAQEBBQAD\n" +
                                "gY0AMIGJAoGBAIRi1eKJwXwx/eyWxyWKGoLuTV1jrXovXqrcdwYCrIUkerrR/BQYYBAALWWcXMSL\n" +
                                "c7rqLa5LUdiaoicYb7Ap4R89MhBLkUJGMGiTY80xDyM8M52CDCk6J+ic7gZJdH2EZ2mjNTU2gFkQ\n" +
                                "ubrX1h+Ky3ihkcW6XrDIQNgPXADaTaD5AgMBAAEwDQYJKoZIhvcNAQEEBQADgYEAEl+PX7+IDhtF\n" +
                                "RMgSPw79R2J6LxnhH+dUrCaw9HQAKeCopMnvhxqdSJ3s3fNCN0Jtgwb/ZAvRRZIc8XwXiD9RMPtk\n" +
                                "RlRt8MDotNXwV8um1XPZAIXqRt9z4VqR42I3SIeToR08UCJN6YJ+Hfoz4foWzm1YtE/Uu3FeiqVA\n" +
                                "vanI4ig=";

                    }

                    //(2)第三方接入平台私钥，由互联网服务平台统一分配.
                    @Override
                    public String getPrivateKey() {
                        return "/u3+7QAAAAIAAAABAAAAAQAPZXh0cmFuZXRfMDAwMzQ2AAABWvosYasAAAK6MIICtjAOBgorBgEE\n" +
                                "ASoCEQEBBQAEggKi4OejCT/nhWy2ThJTlmo4RWKpUPymdDxoHz8tua359oQ9rnMIkZNV7YToQoMS\n" +
                                "aQZXYOxuKzrOkXBThEffBqZjqCKDNkHFXw70HTZoDGdAm3GdgZ4FLiNt4xEiDXd++M63YmL0oiNK\n" +
                                "C4sSriq8x+yDZ6a7r98wPRe+r9zSdvvE8seDfRBgc5Dwom3x5kjRVDESw7dL2riIuph9IKLo3azd\n" +
                                "NXBBOr31DvZH3CBRqz3pXWPOh851Nh9vhYzFlXfSkmnLzEybXVZj9IOX+1LUTQnGd1HwsBpNZbEm\n" +
                                "OJd2Q18mPgGD0z2fLRS+baJud8FrK3e0oUdwAlgd8NwxI0j+iCL/Qicin1lSByIFURHtiDgl+BMT\n" +
                                "Ms03JC/MXHCi9DpsuM1+KnAnIsbdH9bmORHv9x/GoBtpRiqa0x3rYwTXyWkBDiPdMeENCgXTwo24\n" +
                                "AAp5zhRBqRBvTTc74wMwqBuFdQ11yG0I5JCJB7DN/mJKxhNhkhvSpn1Ajf1YloR9FtGGZXHQ7vFn\n" +
                                "f2lSJ0Zq5st5I4NUy4opAz646X5562jxuzfd3PtGYf+IaDIEeksVDF1N8tNvS+7zIQinQItIJobR\n" +
                                "4Wz6Wvt9Cj6K1xJSzmZr9u4TYNUkWnqvOnAXILIZf/IYeZRQ3pMpKDY4YLdVYGAZcy/e+jTDsp9B\n" +
                                "dQyJayBOvGxSMcVUaLH6BFIfkRYCjuF+9/TXvqNt77xXjQ2czwKCjpocZ1cwrouiEiSNzT8uozue\n" +
                                "pH5BsdtLhw9QrQwzjDYklt1NVAmAzGAsnIAGHq8ntgp6qDFI2C1S1u7gi+KPfnWoZnanEosiP0tL\n" +
                                "34ToDHFoz3bIWXbMczYPmidYccCMwWo0r/8fNg88YtJunnHPn6u3HUkc5feYmtgqoGe4Mt9XiVno\n" +
                                "IdgAAAABAAVYLjUwOQAAAqEwggKdMIICBqADAgECAgRY04AYMA0GCSqGSIb3DQEBBAUAMIGSMQkw\n" +
                                "BwYDVQQGEwAxCTAHBgNVBAgTADETMBEGA1UEBxMKMjAyNy0wMy0yMDETMBEGA1UEChMKMjAxNy0w\n" +
                                "My0yMDE/MD0GA1UECww254Of5Y+w5biC5YWs5a6J5bGA5LqS6IGU572R5Yqg5YWs5a6J5pS/5Yqh\n" +
                                "5pyN5Yqh5bmz5Y+wMQ8wDQYDVQQDEwYwMDAzNDYwHhcNMTcwMzIzMDc1ODE2WhcNMjcwMzIxMDc1\n" +
                                "ODE2WjCBkjEJMAcGA1UEBhMAMQkwBwYDVQQIEwAxEzARBgNVBAcTCjIwMjctMDMtMjAxEzARBgNV\n" +
                                "BAoTCjIwMTctMDMtMjAxPzA9BgNVBAsMNueDn+WPsOW4guWFrOWuieWxgOS6kuiBlOe9keWKoOWF\n" +
                                "rOWuieaUv+WKoeacjeWKoeW5s+WPsDEPMA0GA1UEAxMGMDAwMzQ2MIGfMA0GCSqGSIb3DQEBAQUA\n" +
                                "A4GNADCBiQKBgQCtKZLaIqnUYUR6JEBVt0o3VkF/lkcEcWWGLK8SNHVzPp4ZP1/hQJELcrmxiTlr\n" +
                                "YScXI552Un53tGI1F49j5H3K5iNxJc3j4NCGatOf3YeuiQQ9OvO5TLhiH42fgyvwPcOeNw3kX5J7\n" +
                                "qkNoTNdJP1dST76FQH5P/CS/BG2iK3Ts6QIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAFPXzSGHyjUY\n" +
                                "t/nF/sE4FSplSiqh+LanZ0ctQgsqgGtyP99jKqistO85DqwKbCM3mKIrVpjc6XMRbr0I9lKomhfl\n" +
                                "ANFlSJ7CILdGpJIOq6XQwWgiX2Qz2SEY8lWTSw60ntMVJb+xSia2JgMayk/T8fKqZtjYhSXFh/Vm\n" +
                                "tR6ZBwEnuEd61hGSo1ZAL9+p1wSmmjxKR+U=";
                    }

                    //(3)第三方接入平台RSA算法密码，由互联网服务平台统一分配.
                    @Override
                    public String getPassword() {
                        return "8vWsMXUMU4z9nXdH";
                    }


                    //(4)返回clientID,由互联网服务平台统一分配.
                    @Override
                    public String getClientId() {
                        return clientId;
                    }

                    //(5)第三方接入平台获取AesToken算法。请参考实现
                    @Override
                    public AesToken getToken(CryptInfo info) {
                        return getTokenHard(info);
                    }
                },
                //参数二：NetServiceInvoker的java对象序列化封装类。要求将java对象序列化为json后，转化为byte[].其他格式，服务端不识别
                new IObjectByteArrayConverter() {
                    @Override
                    public byte[] convert(Object o) {
                        String serialize = ObjectJsonSerializer.serialize(o);
                        if (StringUtils.isNotBlank(serialize)) {
                            try {
                                return serialize
                                        .getBytes(ProtocolConstants.APP_CHARSET_UTF8);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }

                        return new byte[0];
                    }

                    //可以不实现
                    @Override
                    public Object toBean(byte[] bytes) {
                        return null;
                    }
                });

    }

    public String isRegister(String sfzmmc, String sfzmhm, String sjhm)
            throws Exception {
        // 构造Request对象
        NetClientRequest clientRequest = buildRequest();
        // InterfaceId 与 FunctionId对应接口编号
        // 其中1001为 自动登录接口
        // 1002为 注册用户信息查询接口
        clientRequest.setInterfaceId("1001");
        clientRequest.setFunctionId("1001");
        // clientRequest.setInterfaceId("1002");
        // clientRequest.setFunctionId("1002");
        clientRequest.setRequestUrl(apiUrl);

        // 获取Token令牌用于AES加解密
        AesToken tokenHard = getTokenHard(new CryptInfo(
                clientRequest.getCryptType(), clientRequest.getClientId(),
                clientRequest.getMajor(), clientRequest.getMinor()));
        clientRequest.setClientId(clientId);// 必须，标明客户端身份。
        clientRequest.setMinor(tokenHard.getVersion());// 必须,token的版本就是我们协议请求的minor（小版本）

        // 构造业务请求参数
        VertifyUserBean vertifyUserBean = new VertifyUserBean();
        vertifyUserBean.setSfzmmc(sfzmmc);
        vertifyUserBean.setSfzmhm(sfzmhm);
        vertifyUserBean.setSjhm(sjhm);
        vertifyUserBean.setGnid("3001");//违法处理

        if (vertifyUserBean.getSfzmhm() != null) {
            clientRequest.setData(JSONObject.fromObject(vertifyUserBean)
                    .toString());
        }

        // 执行请求，获取返回结果
        NetClientResponse result = invoker.doPost(clientRequest);

        this.result = result.getData().toString();

        log.info("code:{},mes:{},data:{}" + result.getData().toString());
        return result.getData().toString();
    }

    public AesToken getTokenHard(CryptInfo info) {
        if (Login122Controller.token == null || isExpired(Login122Controller.token)) {
            NetClientRequest clientRequest = buildRequest();
            //线上环境 请切换此url为 http://gab.122.gov.cn/ws/m/token/generate
            clientRequest.setRequestUrl("http://gab.122.gov.cn/ws/m/token/generate");//生成token服务类。
            clientRequest.setCryptType(IHttpCryptData.CryptType.RSA_CRYPT);//token生成过程采用rsa算法。
            clientRequest.setCompressType(IHttpCompressData.CompressType.GZIP);
            clientRequest.setClientId(info.getClientId());
            try {
                NetClientResponse response = invoker.doPost(clientRequest);
                System.out.println("code:{},mes:{},data:{}"
                        + response.getData().toString());
                this.result = response.getData().toString();
                AesResult token = ObjectJsonSerializer.deSerialize(
                        AesResult.class, response.getData().toString());
                Login122Controller.token = token.getData();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Login122Controller.token;
    }

    protected boolean isExpired(AesToken token) {
        if (StringUtils.isBlank(token.getExpiry())){
            return true;
        }else{
            return new Date().after(new Date(Long.valueOf(token.getExpiry())));
        }
    }

    public static String getResult() {
        return result;
    }

    protected NetClientRequest buildRequest() {
        NetClientRequest clientRequest = new NetClientRequest();
        clientRequest.setSiteId(siteId);
        clientRequest.setServerId(serverId);// 互联网省份代码
        clientRequest.setClientId(clientId);//分配给第三方系统的代码
        clientRequest.setMajor(String.valueOf(ProtocolConstants.HEADER_MARJOR));
        clientRequest.setCompressType(HttpCompressData.CompressType.GZIP);
        clientRequest.setCryptType(IHttpCryptData.CryptType.AES_CRYPT);//普通请求采用aes算法，aes算法中的token，使用rsa算法加密请求。
        return clientRequest;
    }
}
